<?php

namespace think\auth\model;

use think\Model;
use think\Collection;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class UserModel extends Model
{

    public function __construct($data = [])
    {
        $this->name = config('auth.user.table');
        parent::__construct($data);
    }

    /**
     * 检查是否有此权限.
     * @param string $permission
     * @return bool
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function Can(string $permission): bool
    {
        if ($this->isSuper()) return true;

        $permissions = $this->Permissions()->column('name');

        return in_array($permission, $permissions);
    }

    /**
     * 是否超级管理员.
     * @return bool
     */
    public function isSuper(): bool
    {
        $superId = config('auth.superId');
        if(empty($superId) || !is_string($superId)) return false;

        $superIds = str_contains($superId, '|') ? explode('|', $superId) : [$superId];

        return in_array($this->id, $superIds);
    }

    /**
     * 获取用户下所有角色.
     * @return RoleModel|null
     */
    public function Role(): RoleModel|null
    {
        return RoleModel::FindById($this->role);
    }

    /**
     * 获取用户权限（所属分组）.
     * @return Collection
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function Permissions(): Collection
    {
        // 超级管理员 默认全部规则
        if ($this->isSuper()) {
            return PermissionModel::select();
        }
        $role = $this->Role();
        $permissions = $role ? array_unique($role->Permissions()->column('name')) : [];
        return PermissionModel::whereIn('name', implode(',', $permissions))->select();
    }

    /**
     * 给用户赋予角色
     * @param RoleModel $role
     * @return bool
     */
    public function AssignRole(RoleModel $role): bool
    {
        return $this->save(['role'=>$role->id]);
    }

    /**
     * 注销用户角色
     * @return bool
     */
    public function RemoveRole(): bool
    {
        return $this->save(['role'=>0]);
    }

    /**
     * 获取用户.
     * @param string $name
     * @return UserModel|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function FindByName(string $name): UserModel|null
    {
        return self::where(['username' => $name])->find();
    }

    /**
     * 根据ID获取用户.
     * @param int|string $uid
     * @return UserModel|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function FindById(int|string $uid): UserModel|null
    {
        return self::where([config('auth.user.primaryKey') => $uid])->find();
    }

    /**
     * 根据别名查找用户
     * @param string $alias
     * @return UserModel|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function FindByAlias(string $alias): UserModel|null
    {
        return self::where(['alias' => $alias])->find();
    }
}
